<?php

define('PAGE_LIMIT', 1);

function list_software()
{
    drupal_set_title(t('List of recently software'));
    
    if (!empty($_GET['page'])) {
      $page = $_GET['page'];
    } else {
      $page = 1;
    }
    
    $end = $page * PAGE_LIMIT;
    $start = $end - PAGE_LIMIT;
    
    $query = db_select('sc_software', 'e');
    $query->join('users', 'u', 'u.uid = e.user_id');
    $query->fields('e', array('scs_id', 'scs_name', 'scs_alias', 'date_create'));
    $query->fields('u', array('name'));
    $query->orderBy('e.date_create', 'DESC');
    $query->condition('e.release', SCS_RELEASE, '=');
    $query->range($start, $end);
    $result = $query->execute();
    $scSoftwares = $result->fetchAll();
    
    $variables['countRow'] = countSoftware();
    $variables['scSoftwares'] = $scSoftwares;
    $variables['page'] = $page;
    
    if ($scSoftwares) {
        return theme_render_template(drupal_get_path('module', 'sckeys') . '/tpl/list_software.tpl.php', $variables);
    }
}

function search_software()
{
    $scsNameExp = explode(' ', trim($_GET['key-word']));
    $or = '';
    for ($i = 0; $i < count($scsNameExp); $i++) {
        if ($scsNameExp[$i] != '') {
            $or .= " OR scs_name LIKE '%" . $scsNameExp[$i] . "%'";
        }
    }

    if ($or != '') {
        $or = substr($or, 4); // cat bo "OR " o dau chuoi
        $where = $or;

        $rows = db_select('sc_software', 'e')
                        ->fields('e', array('scs_id', 'scs_name', 'scs_alias'))
                        //->condition('release', 1)
                        ->where($where)->execute()->fetchAll();
        if ($rows) {
            $li = '';
            foreach ($rows as $row) {
                $li .= '<li>' . l($row->scs_name, 'shortcut-keys/' . $row->scs_id . '/' . $row->scs_alias) . '</li>';
            }

            return '<ul class="item-list">' . $li . '</ul>';
        } else {
            return '<p>Not found <b>' . $_GET['key-word'] . '</b> in software list.</p>';
        }
    } else {
        
    }
}

function sc_detail()
{

    global $scs_id, $base_url;

    $scs_id = arg(1);

    drupal_add_js('var scsId = ' . $scs_id . ';var baseUrl = "' . $base_url . '";', 'inline');
    drupal_add_js(drupal_get_path('module', 'sckeys') . '/js/pages_view_sc_comment.js');

    $sc_keys = db_select('sc_keys', 'e')
            ->addTag('translatable')
            ->fields('e')
            ->condition('e.scs_id', $scs_id)
            ->orderBy('e.sck_id', 'DESC')
            ->execute()
            ->fetchAll();

    $html_str = '';
    $html_str .= '<div style="text-align: right"><a href="' . $base_url . '/shortcut-keys/print/' . $scs_id . '" class="icon-print" target="_blank">Print</a>&nbsp;<a href="#" class="icon-email">Email</a></div>';
    $html_str .= '<div class="email-wrapper" style="display: block;">' . formEmail() . '</div>';
    $html_str .= '
            <table width="99%" id="tbl-keys">
              <thead>
                <th>Keys</th>
                <th>Descriptions</th>
                <th>Extentions</th>
              </thead>
              <tbody>';

    if ($sc_keys) {
        foreach ($sc_keys as $sc_key) {
            $html_str .= '<tr id="row-' . $sc_key->sck_id . '">';
            $html_str .= '<td id="col-key">' . formatKey($sc_key->sck_key) . '</td>';
            $html_str .= '<td id="col-contents">' . $sc_key->sck_contents . '</td>';
            $html_str .= '<td>' . $sc_key->video_id . '</td>';
            $html_str .= '</tr>';
        }
    }
    $html_str .= '</tbody></table>';

    $html_str .= '<div id="sc-comments">' . view_sc_comment($scs_id) . '</div>';

    return $html_str;
}

function sc_list()
{
    
}

function view_sc_comment($scs_id)
{

    global $user;

    $rows = db_select('sc_comments', 'e')
            ->fields('e')
            ->condition('scs_id', $scs_id)
            ->execute()
            ->fetchAll();

    $html = '';
    if ($rows) {
        foreach ($rows as $row) {
            $user_arr = sckeys_dbload_user($row->user_id);
            if ($user_arr) {
                $html .= '<div class="" style="margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #E9E9E9">
                    <table border="0" cellpadding="2" cellspacing="2">
                        <tr>
                            <td valign="top" bgcolor="white" width="60">
                            </td>
                            <td valign="top"  bgcolor="white">
                                <b>' . l($user_arr->name, 'profile/' . $user_arr->uid) . '</b><br/>
                                <span style="color: #999999">
                                    ' . formatTime($row->date_create) . '
                                </span><br/>
                                ' . $row->contents . '
                            </td>
                        </tr>
                    </table>
                </div>';
            }
        }
    }

    if ($user->uid != 0) {
        $html .= ' <div id="form-add-comment">
        <table border="0" cellpadding="2" cellspacing="2">
            <tr>
                <td valign="top" bgcolor="white" width="60">
                </td>
                <td valign="top" bgcolor="white">
                    <a href="#" style="color: #0071B3; font-weight: bold">Write a comment</a><br/>
                    <textarea id="comment_content" cols="70" rows="2"></textarea>
                    <input onclick="submitComment(); return false;" type="submit" class="form-submit" value="Submit" name="op" id="edit-submit">
                    <span id="loading-incator"></span>
                </td>
            </tr>
        </table>
    </div>';
    }

    return $html;
}

function post_comments_add()
{
    global $user;
//  print_r($_POST);die;
    $id = db_insert('sc_comments')
            ->fields(array(
                'scs_id' => $_POST['scsId'],
                'contents' => $_POST['contents'],
                'date_create' => date('Y-m-d H:m:i', time()),
                'user_id' => $user->uid,
            ))
            ->execute();
    if ($id > 0) {
        print 'success';
    } else {
        print 'failed';
    }
}

function sc_print()
{

    $scs_id = arg(2);
    $softWare = load_software($scs_id);

    $sc_keys = db_select('sc_keys', 'e')
            ->addTag('translatable')
            ->fields('e', array('sck_key', 'sck_contents'))
            ->condition('e.scs_id', $scs_id)
            ->orderBy('e.sck_id', 'DESC')
            ->execute()
            ->fetchAll();

    $html_str = '
    <style type="text/css">
    .content {
      width: 650px;
      margin: 0 auto;
      font-family: arial;
      padding-top: 15px;
    }
    .title{text-align: center;}
      table {
          border-collapse: collapse;
          font-size: 0.857em;
          width: 100%;
      }
      table tr th, table tr th a, table tr th a:hover {
          color: #FFFFFF;
          font-weight: bold;
      }
      table tr th {
        text-align: center;
        padding-top: 5px;
        padding-bottom: 4px;
        background-color: #777777 !important;
      }
      table tr td {
        font-size: 1.2em;
        border: 1px solid #999999;
        padding: 3px 7px 2px 7px;
      }
      table tr th {
        border: 1px solid #555555 !important;
      }
    </style>
    ';
    $html_str .= '
    <div class="content">
    <div class="title"> <h2>' . $softWare->scs_name . '</h2></div>
            <table width="99%" id="tbl-keys">
              <thead>
                <th>Keys</th>
                <th>Descriptions</th>
              </thead>
              <tbody>';

    if ($sc_keys) {
        foreach ($sc_keys as $sc_key) {
            $html_str .= '<tr>';
            $html_str .= '<td id="col-key">' . formatKey($sc_key->sck_key) . '</td>';
            $html_str .= '<td id="col-contents">' . $sc_key->sck_contents . '</td>';
            $html_str .= '</tr>';
        }
    }
    $html_str .= '</tbody></table>';

    print $html_str;
}

function post_comments_list()
{
    print view_sc_comment($_POST['scsId']);
}

function formEmail()
{
    global $base_url;
    $pathSend = $base_url . '/' . current_path();
    $html = '
    <table>
    <tr>
      <td><input type="text" name="title" id="title" /></td>
      <td><input type="text" name="sender" id="sender"/></td>
    </tr>
    <tr>
      <td><input type="text" name="email_from" id="email_from"/></td>
      <td><input type="text" name="email_to" id="email_to"/></td>
    </tr>
    <tr>
      <td colspan="2"><textarea name="contents" id="contents"></textarea></td>
    </tr>
    <tr class="tr-button">
      <td colspan="2" align="center" style="text-align: center">
        <button onclick="sendMail(); return false;">Send</button>
        <button onclick="cancel(); return false;">Cancel</button>
        <input name="path_send" id="path_send" type="hidden" value="' . $pathSend . '"/>
      </td>
    </tr>
    </table>
    ';
    return $html;
}

function sc_send_mail()
{

    $mailSuccess = drupal_mail('sckeys', 'composemessage', $_POST['email_to'], 'vi', $_POST, $_POST['email_from'], true);
    if ($mailSuccess) {
        print 'success';
    } else {
        print 'failed';
    }
}

function sckeys_mail($key, &$message, $params)
{
    $message['body'][] = 'Xin chào.';
    $message['body'][] = t($params['email_from'] . 'đã chia sẻ cho bạn link dưới đây từ webiste http://wikishortcut.com') . ':<br/><br/>';
    $message['body'][] = $params['contents'] . ':<br/><br/><br/>';
}

function countSoftware() {
  $query = db_select('sc_software', 'e');
    $query->join('users', 'u', 'u.uid = e.user_id');
    $query->fields('e', array('scs_id'));
    $query->orderBy('e.date_create', 'DESC');
    $query->condition('e.release', SCS_RELEASE, '=');
    $result = $query->execute();
    return $result->rowCount();
}

?>